<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/%E5%8D%9A%E5%AE%A2.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/%E5%8D%9A%E5%AE%A2.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/%E5%8D%9A%E5%AE%A2.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="java,java集合容器," />





  <link rel="alternate" href="/atom.xml" title="Createsequence's Blog" type="application/atom+xml" />






<meta name="description" content="概述 HashMap 是 Map 接口下一个线程不安全的，基于哈希表的实现类。由于他解决哈希冲突的方式是分离链表法，也就是拉链法，因此他的数据结构是数组+链表，在 JDK8 以后，当哈希冲突严重时，HashMap 的链表会在一定条件下转为红黑树以优化查询性能，因此在 JDK8 以后，他的数据结构是数组+链表+红黑树。 对于 HashMap ，作为集合容器，我们需要关注其数据的存储结构，迭代方式，能">
<meta property="og:type" content="article">
<meta property="og:title" content="java集合源码分析（六）：HashMap">
<meta property="og:url" content="http://blog.xiajibagao.top/2020/12/16/java/%E9%9B%86%E5%90%88%E7%B1%BB%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/java%E9%9B%86%E5%90%88%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90%EF%BC%88%E5%85%AD%EF%BC%89%EF%BC%9AHashMap/index.html">
<meta property="og:site_name" content="Createsequence&#39;s Blog">
<meta property="og:description" content="概述 HashMap 是 Map 接口下一个线程不安全的，基于哈希表的实现类。由于他解决哈希冲突的方式是分离链表法，也就是拉链法，因此他的数据结构是数组+链表，在 JDK8 以后，当哈希冲突严重时，HashMap 的链表会在一定条件下转为红黑树以优化查询性能，因此在 JDK8 以后，他的数据结构是数组+链表+红黑树。 对于 HashMap ，作为集合容器，我们需要关注其数据的存储结构，迭代方式，能">
<meta property="og:locale">
<meta property="og:image" content="http://img.xiajibagao.top/image-20201208205304527.png">
<meta property="og:image" content="http://img.xiajibagao.top/image-20201208205304527.png">
<meta property="og:image" content="http://img.xiajibagao.top/image-20201209140746276.png">
<meta property="og:image" content="http://img.xiajibagao.top/image-20201209142455463.png">
<meta property="og:image" content="http://img.xiajibagao.top/未命名文件.jpg">
<meta property="og:image" content="http://img.xiajibagao.top/image-20201217204231973.png">
<meta property="article:published_time" content="2020-12-15T16:00:00.000Z">
<meta property="article:modified_time" content="2021-02-27T12:44:05.406Z">
<meta property="article:author" content="Createsequence">
<meta property="article:tag" content="java">
<meta property="article:tag" content="java集合容器">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://img.xiajibagao.top/image-20201208205304527.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://blog.xiajibagao.top/2020/12/16/java/集合类源码分析/java集合源码分析（六）：HashMap/"/>





  <title>java集合源码分析（六）：HashMap | Createsequence's Blog</title>
  








<meta name="generator" content="Hexo 5.2.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Createsequence's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">一个努力前进的程序猿</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.xiajibagao.top/2020/12/16/java/%E9%9B%86%E5%90%88%E7%B1%BB%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/java%E9%9B%86%E5%90%88%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90%EF%BC%88%E5%85%AD%EF%BC%89%EF%BC%9AHashMap/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/Createsequence.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Createsequence's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">java集合源码分析（六）：HashMap</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-12-16T00:00:00+08:00">
                2020-12-16
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/java%E9%9B%86%E5%90%88%E5%AE%B9%E5%99%A8/" itemprop="url" rel="index">
                    <span itemprop="name">java集合容器</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  11.3k
                </span>
              

              

              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="概述">概述</h2>
<p>HashMap 是 Map 接口下一个线程不安全的，基于哈希表的实现类。由于他解决哈希冲突的方式是分离链表法，也就是拉链法，因此他的数据结构是数组+链表，在 JDK8 以后，当哈希冲突严重时，HashMap 的链表会在一定条件下转为红黑树以优化查询性能，因此在 JDK8 以后，他的数据结构是数组+链表+红黑树。</p>
<p>对于 HashMap ，作为集合容器，我们需要关注其数据的存储结构，迭代方式，能否存放空值；作为使用了数组作为底层结构的集合，我们还需要关注其扩容的实现；同时，针对哈希表的特性，我们还需要关注它如何通过哈希算法取模快速定位下标。</p>
<blockquote>
<p>这是关于 java 集合类源码的第六篇文章。往期文章：</p>
<ol>
<li><a href="https://blog.xiajibagao.top/2020/11/25/java/%E9%9B%86%E5%90%88%E7%B1%BB%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/java%E9%9B%86%E5%90%88%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90%EF%BC%88%E4%B8%80%EF%BC%89%EF%BC%9ACollection%E4%B8%8EAbstractCollection/">java集合源码分析（一）：Collection 与 AbstractCollection</a></li>
<li><a href="https://blog.xiajibagao.top/2020/11/27/java/%E9%9B%86%E5%90%88%E7%B1%BB%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/java%E9%9B%86%E5%90%88%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90%EF%BC%88%E4%BA%8C%EF%BC%89%EF%BC%9AList%E4%B8%8EAbstractList/">java集合源码分析（二）：List与AbstractList</a></li>
<li><a href="https://blog.xiajibagao.top/2020/12/02/java/%E9%9B%86%E5%90%88%E7%B1%BB%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/java%E9%9B%86%E5%90%88%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90%EF%BC%88%E4%B8%89%EF%BC%89%EF%BC%9AArrayList/">java集合源码分析（三）：ArrayList</a></li>
<li><a href="https://blog.xiajibagao.top/2020/12/03/java/%E9%9B%86%E5%90%88%E7%B1%BB%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/java%E9%9B%86%E5%90%88%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90%EF%BC%88%E5%9B%9B%EF%BC%89%EF%BC%9ALinkedList/">java集合源码分析（四）：LinkedList</a></li>
<li><a href="https://blog.xiajibagao.top/2020/12/07/java/%E9%9B%86%E5%90%88%E7%B1%BB%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/java%E9%9B%86%E5%90%88%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90%EF%BC%88%E4%BA%94%EF%BC%89%EF%BC%9AMap%E4%B8%8EAbstractMap/">java集合源码分析（五）：Map与AbstractMap</a></li>
</ol>
</blockquote>
<h2 id="一-hashmap-的数据结构">一、HashMap 的数据结构</h2>
<img src="http://img.xiajibagao.top/image-20201208205304527.png" alt="HashMap的数据结构" style="zoom:67%;">
<p><strong>在 JDK8 之前，HashMap 的数据结构是数组+链表。在 JDK8 以后是数组 + 链表 + 红黑树</strong>。</p>
<p>在 HashMap 中，每一个 value 都被存储在一个 Node 或 TreeNode 实例中，容器中有一个 <code>Node[] table</code> 数组成员变量，数组中的每一格称为一个“桶”。当添加元素时，根据元素的 key 通过哈希值计算得到对应下标，将 Node 类的形式存入“桶”中。如果 table 容量不足时，就会发生扩容，同时对容器内部的元素进行重哈希。</p>
<p>当发生哈希冲突，也就是不同元素计算得到了相同的下标时，会将节点接到“桶”的中的第一个元素后，后续操作亦同，最后就会形成链表。</p>
<p>在 JDK8 以后，由于考虑到<strong>哈希冲突严重时，“桶”中的链表会影响查询效率，因此在一定条件下，链表元素多到一定程度，Node 就会转为 TreeNode，也就是把链表转为红黑树</strong>。</p>
<p>对于红黑树，可以简单理解为不要求严格平衡的平衡二叉树，他保证了查找效率的同时，又保持了较低的的旋转次数。通过这种数据结构，保证了哈希冲突严重的情况下的查找效率。</p>
<h2 id="二-hashmap的成员变量">二、HashMap的成员变量</h2>
<p>由于 HashMap 本身继承了 AbstractMap 抽象类的成员变量，再加上自身的成员变量，以及由于扩容时的重哈希需要的参数，因此 HashMap 的成员变量比较复杂。按照来源以及用途，我们将他的成员变量分为三类：</p>
<h3 id="1来自父类的变量">1.来自父类的变量</h3>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 1.存放key的Set集合视图，通过 keySet()方法获取</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">transient</span> Set&lt;K&gt; keySet;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 1.存放value的Collection集合视图，通过values()方法获取</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">transient</span> Collection&lt;V&gt; values;</span><br></pre></td></tr></table></figure>
<h3 id="2自己的变量">2.自己的变量</h3>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 1.结构更改次数。用于实现并发修改情况下的fast-fail机制，同AbstractList</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">transient</span> <span class="keyword">int</span> modCount;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 2.集合中的元素个数</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">transient</span> <span class="keyword">int</span> size;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 3.存放集合中键值对对象Entry的Set集合视图，通过entrySet()获取</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">transient</span> Set&lt;Map.Entry&lt;K,V&gt;&gt; entrySet;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 4.集合中的桶数组。桶即是当链表或者红黑树的容器</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">transient</span> Node&lt;K,V&gt;[] table;</span><br></pre></td></tr></table></figure>
<h3 id="3扩容相关的变量和常量">3.扩容相关的变量和常量</h3>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 1.默认初始容量。必须为2的幂，默认为16</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> DEFAULT_INITIAL_CAPACITY = <span class="number">1</span> &lt;&lt; <span class="number">4</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 2.最大容量。不能超过1073741824，即Integer.MAX_VALUE的一半</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> MAXIMUM_CAPACITY = <span class="number">1</span> &lt;&lt; <span class="number">30</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 3.扩容阈值。负载系数与容量的乘积，当元素个数超过该值则扩容。默认为0</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">int</span> threshold;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 4.负载系数。当容器内元素数量/容器容量大于等于该值时发生扩容</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">final</span> <span class="keyword">float</span> loadFactor;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 5.默认负载系数。未在构造函数中指定则默认为0.75</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">float</span> DEFAULT_LOAD_FACTOR = <span class="number">0.75f</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 6.容器中桶的最小树化阈值。当容器中元素个数大于等于该值时，桶才会发生树化。</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> MIN_TREEIFY_CAPACITY = <span class="number">64</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 7.桶的树化阈值。当容器元素个数大于等于MIN_TREEIFY_CAPACITY，并且桶中元素个数大于等于该值以后，将链表转为红黑树</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> TREEIFY_THRESHOLD = <span class="number">8</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 8.桶的链化阈值。当桶中元素个数，或者说链表长度小于等于该值以后，将红黑树转为链表</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> UNTREEIFY_THRESHOLD = <span class="number">6</span>;</span><br></pre></td></tr></table></figure>
<h2 id="三-构造方法">三、构造方法</h2>
<p>HashMap 一共提供了四个构造方法：</p>
<h3 id="1指定容量和负载系数">1.指定容量和负载系数</h3>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">HashMap</span><span class="params">(<span class="keyword">int</span> initialCapacity, <span class="keyword">float</span> loadFactor)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 指定初始容量是否小于0</span></span><br><span class="line">    <span class="keyword">if</span> (initialCapacity &lt; <span class="number">0</span>)</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;Illegal initial capacity: &quot;</span> +</span><br><span class="line">                                           initialCapacity);</span><br><span class="line">    <span class="comment">// 若指定初始容量大于最大容量，则初始容量为最大容量</span></span><br><span class="line">    <span class="keyword">if</span> (initialCapacity &gt; MAXIMUM_CAPACITY)</span><br><span class="line">        initialCapacity = MAXIMUM_CAPACITY;</span><br><span class="line">    <span class="comment">// 初始容量是否为小于0或未初始化</span></span><br><span class="line">    <span class="keyword">if</span> (loadFactor &lt;= <span class="number">0</span> || Float.isNaN(loadFactor))</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;Illegal load factor: &quot;</span> +</span><br><span class="line">                                           loadFactor);</span><br><span class="line">    <span class="comment">// 指定初始容量</span></span><br><span class="line">    <span class="keyword">this</span>.loadFactor = loadFactor;</span><br><span class="line">    <span class="comment">// 下一扩容大小为loadFactor或最接近的2的幂</span></span><br><span class="line">    <span class="keyword">this</span>.threshold = tableSizeFor(initialCapacity);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这里涉及到一个取值的方法 <code>tableSizeFor()</code>：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> <span class="title">tableSizeFor</span><span class="params">(<span class="keyword">int</span> cap)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> n = cap - <span class="number">1</span>;</span><br><span class="line">    n |= n &gt;&gt;&gt; <span class="number">1</span>;</span><br><span class="line">    n |= n &gt;&gt;&gt; <span class="number">2</span>;</span><br><span class="line">    n |= n &gt;&gt;&gt; <span class="number">4</span>;</span><br><span class="line">    n |= n &gt;&gt;&gt; <span class="number">8</span>;</span><br><span class="line">    n |= n &gt;&gt;&gt; <span class="number">16</span>;</span><br><span class="line">    <span class="keyword">return</span> (n &lt; <span class="number">0</span>) ? <span class="number">1</span> : (n &gt;= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + <span class="number">1</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这个方法的用于得到指定容量最接近的2的幂，比如传入1会得到2，传入7会得到8。</p>
<h3 id="2只指定容量">2.只指定容量</h3>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">HashMap</span><span class="params">(<span class="keyword">int</span> initialCapacity)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 使用默认负载系数0.75</span></span><br><span class="line">    <span class="keyword">this</span>(initialCapacity, DEFAULT_LOAD_FACTOR);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="3不指定任何系数">3.不指定任何系数</h3>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">HashMap</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 下一扩容大小为默认大小16，其负载系数默认为0.75，初始容量默认为16</span></span><br><span class="line">    <span class="keyword">this</span>.loadFactor = DEFAULT_LOAD_FACTOR; <span class="comment">// all other fields defaulted</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="4根据指定map集合构建">4.根据指定Map集合构建</h3>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">HashMap</span><span class="params">(Map&lt;? extends K, ? extends V&gt; m)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.loadFactor = DEFAULT_LOAD_FACTOR;</span><br><span class="line">    putMapEntries(m, <span class="keyword">false</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这里涉及到一个将合并集合的方法 <code>putMapEntries()</code>，<code>putAll()</code>方法也是基于这个方法实现的。由于添加还涉及到扩容以及其他方法，这里暂不介绍，等下面再详细的了解。</p>
<h2 id="四-hashmap的内部类">四、HashMap的内部类</h2>
<p>基于前文<a href="https://blog.xiajibagao.top/2020/12/07/java/%E9%9B%86%E5%90%88%E7%B1%BB%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/java%E9%9B%86%E5%90%88%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90%EF%BC%88%E4%BA%94%EF%BC%89%EF%BC%9AMap%E4%B8%8EAbstractMap/">java集合源码分析（五）：Map与AbstractMap</a>中第五部分 “AbstractMap 的视图”里对 AbstractMap 的分析，我们知道，HashMap 作为继承了 AbstractMap 的子类，因此它内部会拥有三个集合视图</p>
<ul>
<li>存放 key 的 Set 集合：<code>Set&lt;K&gt; keySet</code></li>
<li>存放 value 的 Collection 集合：<code>Collection&lt;V&gt; valuse</code></li>
<li>存放 Entry 对象的 Set 集合：<code>Set&lt;Map.Entry&lt;K,V&gt;&gt; entrySet</code></li>
</ul>
<p>同时还需要一个实现了 Entry 接口的内部类作为 entrySet 的元素使用。</p>
<p>因此 HashMap 作为 AbstractMap 的子类，他最少需要 <code>3种集合视图 + 3种结合视图的迭代器 + Entry 实现类</code> 7种内部类。</p>
<p>实际上，由于 JDK8 以后红黑树和并行迭代的需求，他还需要新增 <code>1种Entry红黑树节点实现 + 3种视图容器对应的并行迭代器</code>2种内部类。</p>
<p>由于针对迭代器和并行迭代器又各提取了一个抽象类，所以 HashMap 中一共会有 ：</p>
<p><code>3种视图容器 + 1种迭代器抽象类 + 3种视图容器的迭代器 + 1种并行迭代器抽象类 + 3种视图容器对应的并行迭代器 + 1种Entry实现类 + 1种Entry的红黑树节点实现类</code></p>
<p>总计 13 种内部类</p>
<h3 id="1-node-treenode">1. Node / TreeNode</h3>
<img src="http://img.xiajibagao.top/image-20201208205304527.png" alt="HashMap的数据结构" style="zoom: 50%;">
<p>Node 是 HashMap 中的节点类，在 JDK8 之前对应的是 Entry 类。他是 Map 接口中 Entry 的实现类。</p>
<p>在 HashMap 中数组的每一个位置都是一个“桶”，而“桶”中存放的就是带有数据的节点对象 Node。当哈希冲突时，多个 Node 会在同一个“桶”中形成链表。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">Node</span>&lt;<span class="title">K</span>,<span class="title">V</span>&gt; <span class="keyword">implements</span> <span class="title">Map</span>.<span class="title">Entry</span>&lt;<span class="title">K</span>,<span class="title">V</span>&gt; </span>&#123;</span><br><span class="line">    <span class="comment">// 节点的hashcode</span></span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">int</span> hash;</span><br><span class="line">    <span class="comment">// key</span></span><br><span class="line">    <span class="keyword">final</span> K key;</span><br><span class="line">    <span class="comment">// value</span></span><br><span class="line">    V value;</span><br><span class="line">    <span class="comment">// 下一节点</span></span><br><span class="line">    Node&lt;K,V&gt; next;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在 JDK8，当容器中元素数量大于等于64，并且桶中节点大于等于8的时候，会在扩容前触发红黑树化，Node 类会被转变为 TreeNode ，链表会变成：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">TreeNode</span>&lt;<span class="title">K</span>,<span class="title">V</span>&gt; <span class="keyword">extends</span> <span class="title">LinkedHashMap</span>.<span class="title">Entry</span>&lt;<span class="title">K</span>,<span class="title">V</span>&gt; </span>&#123;</span><br><span class="line">    <span class="comment">// 父节点</span></span><br><span class="line">    TreeNode&lt;K,V&gt; parent;</span><br><span class="line">    <span class="comment">// 左子节点</span></span><br><span class="line">    TreeNode&lt;K,V&gt; left;</span><br><span class="line">    <span class="comment">// 右子节点</span></span><br><span class="line">    TreeNode&lt;K,V&gt; right;</span><br><span class="line">    <span class="comment">// 前驱节点</span></span><br><span class="line">    TreeNode&lt;K,V&gt; prev;</span><br><span class="line">    <span class="comment">// 是否为红色节点</span></span><br><span class="line">    <span class="keyword">boolean</span> red;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>值得一提的是，TreeNode 继承了 LinkedHashMap.Entry 类，但是 LinkedHashMap.Entry 类又继承了 HashMap.Node，因此，实际上 TreeNode 也是 Node 类的子类，这是 Node 转变为 TreeNode 的结构基础。</p>
<p>另外，TreeNode 尽管是树，但是他仍然通过 prev 维持了隐式的链表结构，理论上每一个节点都可以获取他上一次插入的节点，这仍然可以理解为单向链表。</p>
<h3 id="2-keyset-keyiterator">2.  KeySet / KeyIterator</h3>
<p><code>Set&lt;K&gt; keySet</code> 是在 AbstractMap 中已经定义好了变量，它是一个存放 key 的集合，HashMap 的哈希算法保证了 key 的唯一性，这恰好也符合 Set 集合的特征。在 HashMap 中，<strong>为其提供了实现类 KeySet</strong> 。</p>
<p>KeySet  继承了 AbstractSet 抽象类，并且直接使用 HashMap 中的方法去实现了抽象类中的大多数抽象方法。值得一提的是，他实现的 <code>iterator()</code><strong>返回的也是 HashMap 的一个内部类 KeyIterator</strong>。</p>
<h3 id="3-values-valueiterator">3. Values  /  ValueIterator</h3>
<p>和 KeySet 类一样，<strong>Values 也是给 AbstractMap 中的 <code>Collection&lt;V&gt; values</code> 提供的实现类</strong>，他继承了 AbstractCollection 抽象类，并且使用 HashMap 的方法实现了大部分抽象方法。</p>
<p>同样的，它的<code>iterator()</code>返回的也是 HashMap 的一个<strong>内部类 ValueIterator</strong>。</p>
<h3 id="4-entryset-entryiterator">4. EntrySet  /  EntryIterator</h3>
<p>A<strong>bstractMap 中有一个留给子类去实现的核心抽象方法 <code>entrySet()</code>，而 EntrySet 就是为了实现该方法而创建的类</strong>。它继承了 <code>AbstractSet&lt;Map.Entry&lt;K,V&gt;&gt;</code>，<strong>表示的是容器中的一对键值对对象</strong>。在注释中，作者将其称为视图。</p>
<p>通过 EntrySet 类，我们就可以<strong>像 Collection 的 toArray 一样，将 Map 以 Set 集合视图的形式表现出来</strong>。</p>
<p>同样的，作为一个 AbstractSet 的实现类，HashMap 也专门为其实现了一个<strong>内部迭代器类 EntryIterator</strong> 。EntrySet 的<code>iterator()</code>方法返回的就是该类。</p>
<h3 id="5-hashiterator">5. HashIterator</h3>
<p>HashIterator 类是一个用于迭代 Node 节点的迭代器抽象类，他也是上述 KeyIterator，ValueIterator，EntryIterator <strong>三种内部迭代器类的父类</strong>。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">HashIterator</span> </span>&#123;</span><br><span class="line">    Node&lt;K,V&gt; next;        <span class="comment">// next entry to return</span></span><br><span class="line">    Node&lt;K,V&gt; current;     <span class="comment">// current entry</span></span><br><span class="line">    <span class="keyword">int</span> expectedModCount;  <span class="comment">// for fast-fail</span></span><br><span class="line">    <span class="keyword">int</span> index;             <span class="comment">// current slot</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">boolean</span> <span class="title">hasNext</span><span class="params">()</span> </span>&#123;&#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">final</span> Node&lt;K,V&gt; <span class="title">nextNode</span><span class="params">()</span> </span>&#123;&#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">remove</span><span class="params">()</span> </span>&#123;&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>虽然它叫 HashIterator ，但是它并没有实现 <code>Iterator</code>接口，而是让他的子类自己去实现接口。并且只值提供迭代和删除两种功能的三个方法。</p>
<p>此外，他的子类 KeyIterator，ValueIterator，EntryIterator 也非常朴素，只在它的基础上重写包装了一下 <code>nextNode()</code>作为自己的 <code>next()</code>方法，这里不妨也看成适配器的一种。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">KeyIterator</span> <span class="keyword">extends</span> <span class="title">HashIterator</span></span></span><br><span class="line"><span class="class">    <span class="keyword">implements</span> <span class="title">Iterator</span>&lt;<span class="title">K</span>&gt; </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">final</span> K <span class="title">next</span><span class="params">()</span> </span>&#123; <span class="keyword">return</span> nextNode().key; &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">ValueIterator</span> <span class="keyword">extends</span> <span class="title">HashIterator</span></span></span><br><span class="line"><span class="class">    <span class="keyword">implements</span> <span class="title">Iterator</span>&lt;<span class="title">V</span>&gt; </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">final</span> V <span class="title">next</span><span class="params">()</span> </span>&#123; <span class="keyword">return</span> nextNode().value; &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">EntryIterator</span> <span class="keyword">extends</span> <span class="title">HashIterator</span></span></span><br><span class="line"><span class="class">    <span class="keyword">implements</span> <span class="title">Iterator</span>&lt;<span class="title">Map</span>.<span class="title">Entry</span>&lt;<span class="title">K</span>,<span class="title">V</span>&gt;&gt; </span>&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">final</span> Map.<span class="function">Entry&lt;K,V&gt; <span class="title">next</span><span class="params">()</span> </span>&#123; <span class="keyword">return</span> nextNode(); &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="6-spliterator">6. Spliterator</h3>
<p>跟 Iterator 一样，HashMap 也提供了 HashMapSpliterator，KeySpliterator，ValueSpliterator，EntrySpliterator 四种并行迭代器。后面三者都是 HashMapSpliterator 的子类。</p>
<h2 id="五-hashmap-获取插入下标">五、HashMap 获取插入下标</h2>
<p>HashMap 是基于哈希表实现的，因此添加元素和扩容时通过哈希算法获取 key 对应的数组下标是整整个类进行添加操作的基础。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> V <span class="title">put</span><span class="params">(K key, V value)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> putVal(hash(key), key, value, <span class="keyword">false</span>, <span class="keyword">true</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="1-计算哈希值">1. 计算哈希值</h3>
<p>这里涉及到两个方法，一个是计算哈希值的 <code>hash()</code>方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> <span class="title">hash</span><span class="params">(Object key)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> h;</span><br><span class="line">    <span class="keyword">return</span> (key == <span class="keyword">null</span>) ? <span class="number">0</span> : (h = key.hashCode()) ^ (h &gt;&gt;&gt; <span class="number">16</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这是来自知乎大佬一个非常详细的回答：<a target="_blank" rel="noopener" href="https://www.zhihu.com/question/20733617/answer/32513376">JDK 源码中 HashMap 的 hash 方法原理是什么？ - 知乎</a>；</p>
<p>这里我简单的概括一下：</p>
<p>该方法实际上是一个“扰动函数”，作用是对<code>Object.hashCode()</code>获取到的 hash 值进行<strong>高低位混淆</strong>。</p>
<p><img src="http://img.xiajibagao.top/image-20201209140746276.png" alt="HashMap的哈希算法"></p>
<p>我们可以看到，<strong>符号右移16位后，新二进制数的前16位都为0，后16位就是原始 hashcode 的高16位</strong>。</p>
<p><strong>将原始 hashcode 与 位运算得到的二进制数再进行异或运算以后，我们就得到的 hash 前16全部都为1，后16位则同时混淆了高16位和低16位的特征，进一步增加了随机性。</strong></p>
<p>现在我们得到了 key 的 hashcode，这是计算下标的基础。</p>
<h3 id="2-计算下标">2. 计算下标</h3>
<p>接下来进入<code>putVal()</code>方法，实际上包括 <code>putAll()</code>在内，所有添加/替换元素的方法，都依赖于 <code>putVal()</code>实现。<code>putVal()</code>需要传入 key 的 hash 作为参数，它将根据 hash 值和 key 进行进一步的计算，获取实际 value 要插入的下标。</p>
<p>我们先忽略计算下标以外的其他方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">final</span> V <span class="title">putVal</span><span class="params">(<span class="keyword">int</span> hash, K key, V value, <span class="keyword">boolean</span> onlyIfAbsent,</span></span></span><br><span class="line"><span class="function"><span class="params">               <span class="keyword">boolean</span> evict)</span> </span>&#123;</span><br><span class="line">    Node&lt;K,V&gt;[] tab; Node&lt;K,V&gt; p; <span class="keyword">int</span> n, i;</span><br><span class="line">    ... ...</span><br><span class="line">    <span class="comment">// n 即为当前数组长度</span></span><br><span class="line">    <span class="keyword">if</span> ((tab = table) == <span class="keyword">null</span> || (n = tab.length) == <span class="number">0</span>)</span><br><span class="line">            n = (tab = resize()).length;</span><br><span class="line">    <span class="comment">// 根据 n 与 hash 计算插入下标</span></span><br><span class="line">    <span class="keyword">if</span> ((p = tab[i = (n - <span class="number">1</span>) &amp; hash]) == <span class="keyword">null</span>)</span><br><span class="line">        tab[i] = newNode(hash, key, value, <span class="keyword">null</span>);</span><br><span class="line">    </span><br><span class="line">    ... ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>也就是说，当通过扰动函数<code>hash()</code>获取到了已经混淆高低位的 key 的 hashcode 以后， <strong>会将其与数组长度-1进行与运算</strong>：<code>(n - 1) &amp; hash</code>。</p>
<p>以默认是容量16为例，它转换为二进制数是 10000，而 （16-1）转换为二进制数就是 1111，补零以后它与 <code>hash()</code> 计算得到的 hashcode 进行与运算过程如下：</p>
<p><img src="http://img.xiajibagao.top/image-20201209142455463.png" alt="与运算取模"></p>
<p>在这个过程，之前留下的两个问题就得到了解答：</p>
<h4 id="为什么容量需要是2的幂">为什么容量需要是2的幂？</h4>
<p>我们可以看到，按位的与运算只有 1&amp;1 = 1，<strong>由于数组长度转为二进制只有4位，所有高于4位的位数都为0，因此运算结果高于4位的位置也都会是0，这里巧妙的实现了取模的效果，数组长度起到了低位掩码的作用。这也整是为什么 HashMap 的容量要是2的幂的原因。</strong></p>
<h4 id="为什么要hash要混淆高低位">为什么要<code>hash()</code>要混淆高低位？</h4>
<p>再回头看看 <code>hash()</code>函数，他混合了原始 hashcode 的高位和低位的特征，我们说他增加了随机性，在点要怎么理解呢？</p>
<p>我们举个例子：</p>
<table>
<thead>
<tr>
<th>key</th>
<th>hashCode</th>
<th>不混淆取后四位</th>
<th>混淆后取后四位</th>
</tr>
</thead>
<tbody>
<tr>
<td>808321199</td>
<td>110000001011100000000010101111</td>
<td>1111</td>
<td>0001</td>
</tr>
<tr>
<td>7015199</td>
<td>11010110000101100011111</td>
<td>1111</td>
<td>0100</td>
</tr>
<tr>
<td>9999</td>
<td>10011100001111</td>
<td>1111</td>
<td>1111</td>
</tr>
</tbody>
</table>
<p>实际上，由于取模运算最终只看数组长度转成的二进制数的有效位数，也就是说，数组有效位是4位，那么 key 的 hash 就只看4位，如果是18位，那么 hash 就只看18位。</p>
<p>在这种情况下，如果数组够长，那么 hash 有效位够多，散列度就会很好；<strong>但是如果有效位非常短，比如只有4位，那么对于区分度在高位数字的值来说就无法区分开</strong>，比如表格所示的 808321199，7015199，461539999 三个低位相同的数字，最后取模的时候都会被看成 1111，而混合高低位以后就是 0001，0100，1111，这就可以区分开来了。</p>
<h2 id="六-hashmap-添加元素">六、HashMap 添加元素</h2>
<p>在之前获取下标的例子中，我们知道 <code>put()</code>方法依赖于 <code>putVal()</code>方法，事实上，包括 <code>putAll()</code>在内，所有添加元素的方法都需要依赖于 <code>putVal()</code>。</p>
<p>由于添加元素涉及到整个结构的改变，因而 <code>putVal()</code>中除了需要计算下标，还包含扩容，链表的树化与树的链表化在内的多个过程。</p>
<h3 id="1-putval">1. putVal</h3>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">final</span> V <span class="title">putVal</span><span class="params">(<span class="keyword">int</span> hash, K key, V value, <span class="keyword">boolean</span> onlyIfAbsent,</span></span></span><br><span class="line"><span class="function"><span class="params">               <span class="keyword">boolean</span> evict)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 当前table数组</span></span><br><span class="line">    Node&lt;K,V&gt;[] tab; Node&lt;K,V&gt; p; </span><br><span class="line">    <span class="comment">// 当前数组长度，当前要插入数组位置的下标</span></span><br><span class="line">    <span class="keyword">int</span> n, i;</span><br><span class="line">    <span class="comment">// 若集合未扩容，则进行第一次扩容</span></span><br><span class="line">    <span class="keyword">if</span> ((tab = table) == <span class="keyword">null</span> || (n = tab.length) == <span class="number">0</span>)</span><br><span class="line">        n = (tab = resize()).length;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 获取key对应要插入的下标（即桶）</span></span><br><span class="line">    <span class="keyword">if</span> ((p = tab[i = (n - <span class="number">1</span>) &amp; hash]) == <span class="keyword">null</span>)</span><br><span class="line">        <span class="comment">// 若是桶中没有元素，则添加第一个</span></span><br><span class="line">        tab[i] = newNode(hash, key, value, <span class="keyword">null</span>);</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="comment">// 若已经桶中已经存在元素</span></span><br><span class="line">        Node&lt;K,V&gt; e; K k;</span><br><span class="line">        <span class="comment">// 1.插入元素与第一个元素是否有相同key</span></span><br><span class="line">        <span class="keyword">if</span> (p.hash == hash &amp;&amp; ((k = p.key) == key ||</span><br><span class="line">                               (key != <span class="keyword">null</span> &amp;&amp; key.equals(k))))</span><br><span class="line">            e = p;</span><br><span class="line">        <span class="comment">// 2.桶中的链表是否已经转换为红黑树</span></span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span> (p <span class="keyword">instanceof</span> TreeNode)</span><br><span class="line">            e = ((TreeNode&lt;K,V&gt;)p).putTreeVal(<span class="keyword">this</span>, tab, hash, key, value);</span><br><span class="line">        <span class="comment">// 3.遍历链表，添加到尾端</span></span><br><span class="line">        <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> binCount = <span class="number">0</span>; ; ++binCount) &#123;</span><br><span class="line">                <span class="comment">// 将节点添加到队尾</span></span><br><span class="line">                <span class="keyword">if</span> ((e = p.next) == <span class="keyword">null</span>) &#123;</span><br><span class="line">                    p.next = newNode(hash, key, value, <span class="keyword">null</span>);</span><br><span class="line">                    <span class="comment">// 是否需要转换为红黑树</span></span><br><span class="line">                    <span class="keyword">if</span> (binCount &gt;= TREEIFY_THRESHOLD - <span class="number">1</span>) <span class="comment">// -1 for 1st</span></span><br><span class="line">                        treeifyBin(tab, hash);</span><br><span class="line">                    <span class="keyword">break</span>;</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="comment">// 是否遇到了key相同的节点</span></span><br><span class="line">                <span class="keyword">if</span> (e.hash == hash &amp;&amp;</span><br><span class="line">                    ((k = e.key) == key || (key != <span class="keyword">null</span> &amp;&amp; key.equals(k))))</span><br><span class="line">                    <span class="keyword">break</span>;</span><br><span class="line">                p = e;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 如果key已经存在对应的值</span></span><br><span class="line">        <span class="keyword">if</span> (e != <span class="keyword">null</span>) &#123; <span class="comment">// existing mapping for key</span></span><br><span class="line">            V oldValue = e.value;</span><br><span class="line">            <span class="comment">// 是否要覆盖value</span></span><br><span class="line">            <span class="keyword">if</span> (!onlyIfAbsent || oldValue == <span class="keyword">null</span>)</span><br><span class="line">                e.value = value;</span><br><span class="line">            </span><br><span class="line">            <span class="comment">// 空方法，用于LinkedHashMap插入后的回调</span></span><br><span class="line">            afterNodeAccess(e);</span><br><span class="line">            <span class="keyword">return</span> oldValue;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    ++modCount;</span><br><span class="line">    <span class="comment">// 是否需要扩容</span></span><br><span class="line">    <span class="keyword">if</span> (++size &gt; threshold)</span><br><span class="line">        resize();</span><br><span class="line">    <span class="comment">// 空方法，用于LinkedHashMap插入后的回调</span></span><br><span class="line">    afterNodeInsertion(evict);</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="2链表的树化">2.链表的树化</h3>
<p>在上述过程，涉及到了判断桶中是否已经转为红黑树的操作：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">else</span> <span class="keyword">if</span> (p <span class="keyword">instanceof</span> TreeNode)</span><br><span class="line">    <span class="comment">// 将Node转为TreeNode，并且添加到红黑树</span></span><br><span class="line">    e = ((TreeNode&lt;K,V&gt;)p).putTreeVal(<span class="keyword">this</span>, tab, hash, key, value);</span><br></pre></td></tr></table></figure>
<p>以及将链表转为红黑树的操作：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (binCount &gt;= TREEIFY_THRESHOLD - <span class="number">1</span>) <span class="comment">// -1 for 1st</span></span><br><span class="line">    treeifyBin(tab, hash);</span><br></pre></td></tr></table></figure>
<p>其中，<code>putTreeVal()</code>是添加节点到红黑树的方法，而 <code>treeifyBin()</code>是一个将链表转为红黑树的方法。我们暂且只看看 HashMap 链表是如何转为红黑树的：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">final</span> <span class="keyword">void</span> <span class="title">treeifyBin</span><span class="params">(Node&lt;K,V&gt;[] tab, <span class="keyword">int</span> hash)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> n, index; Node&lt;K,V&gt; e;</span><br><span class="line">    <span class="comment">// table是否小于最小树化阈值64</span></span><br><span class="line">    <span class="keyword">if</span> (tab == <span class="keyword">null</span> || (n = tab.length) &lt; MIN_TREEIFY_CAPACITY)</span><br><span class="line">        <span class="comment">// 如果不到64就直接扩容</span></span><br><span class="line">        resize();</span><br><span class="line">    <span class="keyword">else</span> <span class="keyword">if</span> ((e = tab[index = (n - <span class="number">1</span>) &amp; hash]) != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="comment">// 否则看看桶中是否存在元素</span></span><br><span class="line">        TreeNode&lt;K,V&gt; hd = <span class="keyword">null</span>, tl = <span class="keyword">null</span>;</span><br><span class="line">        <span class="comment">// 将桶中链表的所有节点Node转为TreeNode</span></span><br><span class="line">        <span class="keyword">do</span> &#123;</span><br><span class="line">            TreeNode&lt;K,V&gt; p = replacementTreeNode(e, <span class="keyword">null</span>);</span><br><span class="line">            <span class="keyword">if</span> (tl == <span class="keyword">null</span>)</span><br><span class="line">                hd = p;</span><br><span class="line">            <span class="keyword">else</span> &#123;</span><br><span class="line">                p.prev = tl;</span><br><span class="line">                tl.next = p;</span><br><span class="line">            &#125;</span><br><span class="line">            tl = p;</span><br><span class="line">        &#125; <span class="keyword">while</span> ((e = e.next) != <span class="keyword">null</span>);</span><br><span class="line">        </span><br><span class="line">        <span class="comment">//  如果桶中不为空，就将链表转为红黑树</span></span><br><span class="line">        <span class="keyword">if</span> ((tab[index] = hd) != <span class="keyword">null</span>)</span><br><span class="line">            hd.treeify(tab);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面过程实现了将链表的节点 Node 转为 TreeNode 的过程，接下来 <code>TreeNode.treeify()</code>方法会真正将链表转为红黑树：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">final</span> <span class="keyword">void</span> <span class="title">treeify</span><span class="params">(Node&lt;K,V&gt;[] tab)</span> </span>&#123;</span><br><span class="line">    TreeNode&lt;K,V&gt; root = <span class="keyword">null</span>;</span><br><span class="line">    <span class="comment">// 遍历链表</span></span><br><span class="line">    <span class="keyword">for</span> (TreeNode&lt;K,V&gt; x = <span class="keyword">this</span>, next; x != <span class="keyword">null</span>; x = next) &#123;</span><br><span class="line">        <span class="comment">// 获取下一节点</span></span><br><span class="line">        next = (TreeNode&lt;K,V&gt;)x.next;</span><br><span class="line">        x.left = x.right = <span class="keyword">null</span>;</span><br><span class="line">        <span class="comment">// 队首元素为根节点</span></span><br><span class="line">        <span class="keyword">if</span> (root == <span class="keyword">null</span>) &#123;</span><br><span class="line">            x.parent = <span class="keyword">null</span>;</span><br><span class="line">            x.red = <span class="keyword">false</span>;</span><br><span class="line">            root = x;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">// 不是队首元素，则构建子节点</span></span><br><span class="line">            K k = x.key;</span><br><span class="line">            <span class="keyword">int</span> h = x.hash;</span><br><span class="line">            Class&lt;?&gt; kc = <span class="keyword">null</span>;</span><br><span class="line">            <span class="keyword">for</span> (TreeNode&lt;K,V&gt; p = root;;) &#123;</span><br><span class="line">                <span class="keyword">int</span> dir, ph;</span><br><span class="line">                K pk = p.key;</span><br><span class="line">                <span class="comment">// 向右</span></span><br><span class="line">                <span class="keyword">if</span> ((ph = p.hash) &gt; h)</span><br><span class="line">                    dir = -<span class="number">1</span>;</span><br><span class="line">                <span class="comment">// 向左</span></span><br><span class="line">                <span class="keyword">else</span> <span class="keyword">if</span> (ph &lt; h)</span><br><span class="line">                    dir = <span class="number">1</span>;</span><br><span class="line">                <span class="comment">// 使用比较器进行比较</span></span><br><span class="line">                <span class="keyword">else</span> <span class="keyword">if</span> ((kc == <span class="keyword">null</span> &amp;&amp;</span><br><span class="line">                          (kc = comparableClassFor(k)) == <span class="keyword">null</span>) ||</span><br><span class="line">                         (dir = compareComparables(kc, k, pk)) == <span class="number">0</span>)</span><br><span class="line">                    dir = tieBreakOrder(k, pk);</span><br><span class="line"></span><br><span class="line">                <span class="comment">// 构建子节点</span></span><br><span class="line">                TreeNode&lt;K,V&gt; xp = p;</span><br><span class="line">                <span class="keyword">if</span> ((p = (dir &lt;= <span class="number">0</span>) ? p.left : p.right) == <span class="keyword">null</span>) &#123;</span><br><span class="line">                    x.parent = xp;</span><br><span class="line">                    <span class="keyword">if</span> (dir &lt;= <span class="number">0</span>)</span><br><span class="line">                        xp.left = x;</span><br><span class="line">                    <span class="keyword">else</span></span><br><span class="line">                        xp.right = x;</span><br><span class="line">                    </span><br><span class="line">                    <span class="comment">// 再平衡</span></span><br><span class="line">                    root = balanceInsertion(root, x);</span><br><span class="line">                    <span class="keyword">break</span>;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 再平衡，保证链表头节点是树的根节点</span></span><br><span class="line">    moveRootToFront(tab, root);</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>以上是链表树化的过程，虽然实现过程不简单，但是流程很简单：</p>
<ul>
<li>判断元素总数量是否大于最小树化阈值64；</li>
<li>判断是否链表是否大于8；</li>
<li>将原本链表的Node节点转为TreeNode节点；</li>
<li>构建树，添加每一个子节点的时候判断是否需要再平衡;</li>
<li>构建完后，若原本链表的头结点不是树的根节点，则再平衡确保头节点变为根节点</li>
</ul>
<h4 id="链表转为红黑树的条件">链表转为红黑树的条件</h4>
<p>这里我们也理清楚了链表树化的条件：<strong>一个是链表添加完元素后是否大于8，并且当前总元素数量大于64</strong>。</p>
<p>当不满足这个条件的时候，再添加元素就会直接扩容，利用扩容过程中的重哈希来缓解哈希冲突，而不是转为红黑树。</p>
<h3 id="3为什么key可以为null">3.为什么key可以为null</h3>
<p>我们回顾一下 <code>hash()</code>方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">(key == <span class="keyword">null</span>) ? <span class="number">0</span> : (h = key.hashCode()) ^ (h &gt;&gt;&gt; <span class="number">16</span>);</span><br></pre></td></tr></table></figure>
<p>可以看到，这里对 <code>key == null</code>的情况做了处理，当 key 是 null 的时候，哈希值会直接被作为 hash 为 0 的元素看待，在 <code>putVal()</code>中添加元素的时候还会判断：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (p.hash == hash &amp;&amp; ((k = p.key) == key ||</span><br><span class="line">                       (key != <span class="keyword">null</span> &amp;&amp; key.equals(k))))</span><br></pre></td></tr></table></figure>
<p>由于除了比较 hash 值，还会比较内存地址并调用 equals 比较，所以 null 会被筛出来，作为有且仅有一个的 key 使用。</p>
<h2 id="七-hashmap-的扩容">七、HashMap 的扩容</h2>
<p>现在我们知道了 HashMap 是如何计算下标的，也明白了 HashMap 是如何添加元素的，现在我们该了解添加元素过程中，扩容方法 <code>resize()</code>的原理了。</p>
<h3 id="1-resize">1. resize</h3>
<p><code>resize()</code>是 HashMap 的扩容方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">final</span> Node&lt;K,V&gt;[] resize() &#123;</span><br><span class="line">    Node&lt;K,V&gt;[] oldTab = table;</span><br><span class="line">    <span class="comment">// 当前容量</span></span><br><span class="line">    <span class="keyword">int</span> oldCap = (oldTab == <span class="keyword">null</span>) ? <span class="number">0</span> : oldTab.length;</span><br><span class="line">    <span class="comment">// 上一次的扩容阈值（在上一次扩容时指定）</span></span><br><span class="line">    <span class="keyword">int</span> oldThr = threshold;</span><br><span class="line">    <span class="comment">// 新容量，下一次扩容目标容量</span></span><br><span class="line">    <span class="keyword">int</span> newCap, newThr = <span class="number">0</span>;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//======一、计算并获取扩容目标大小======</span></span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 1.若当前容量大于0（即已经扩容过了）</span></span><br><span class="line">    <span class="keyword">if</span> (oldCap &gt; <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="comment">// 是否大于理论允许最大值</span></span><br><span class="line">        <span class="keyword">if</span> (oldCap &gt;= MAXIMUM_CAPACITY) &#123;</span><br><span class="line">            <span class="comment">// 扩容阈值设置为Integer.MAX_VALUE，本次以后不会再触发扩容</span></span><br><span class="line">            threshold = Integer.MAX_VALUE;</span><br><span class="line">            <span class="keyword">return</span> oldTab;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 若未达到理论允许最大值，并且：</span></span><br><span class="line">        <span class="comment">// (1)本次扩容目标容量的两边小于理论允许最大值</span></span><br><span class="line">        <span class="comment">// (2)当前容量大于默认初始容量16</span></span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span> ((newCap = oldCap &lt;&lt; <span class="number">1</span>) &lt; MAXIMUM_CAPACITY &amp;&amp;</span><br><span class="line">                 oldCap &gt;= DEFAULT_INITIAL_CAPACITY)</span><br><span class="line">            <span class="comment">// 新扩容阈值为当前扩容阈值的两倍</span></span><br><span class="line">            newThr = oldThr &lt;&lt; <span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 2.若本次扩容容量大于0（即还是初始状态，指定了容量，但是是第一次扩容）</span></span><br><span class="line">    <span class="keyword">else</span> <span class="keyword">if</span> (oldThr &gt; <span class="number">0</span>)</span><br><span class="line">        <span class="comment">// 新容量为上一次指定的扩容阈值</span></span><br><span class="line">        newCap = oldThr;</span><br><span class="line">    <span class="comment">// 3.若当前容量和上一次的扩容阈值都为0（即还是初始状态，未指定容量而且也没扩容过）</span></span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="comment">// 使用默认值</span></span><br><span class="line">        newCap = DEFAULT_INITIAL_CAPACITY;</span><br><span class="line">        newThr = (<span class="keyword">int</span>)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">     <span class="comment">//======二、根据指定大小扩容======</span></span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 根据负载系数检验新容量是否可用</span></span><br><span class="line">    <span class="keyword">if</span> (newThr == <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">float</span> ft = (<span class="keyword">float</span>)newCap * loadFactor;</span><br><span class="line">        <span class="comment">// 如果乘上负载系数大于理论允许最大容量，则直接扩容到Integer.MAX_VALUE</span></span><br><span class="line">        newThr = (newCap &lt; MAXIMUM_CAPACITY &amp;&amp; ft &lt; (<span class="keyword">float</span>)MAXIMUM_CAPACITY ?</span><br><span class="line">                  (<span class="keyword">int</span>)ft : Integer.MAX_VALUE);</span><br><span class="line">    &#125;</span><br><span class="line">    threshold = newThr;</span><br><span class="line">    <span class="meta">@SuppressWarnings(&#123;&quot;rawtypes&quot;,&quot;unchecked&quot;&#125;)</span></span><br><span class="line">    Node&lt;K,V&gt;[] newTab = (Node&lt;K,V&gt;[])<span class="keyword">new</span> Node[newCap];</span><br><span class="line">    table = newTab;</span><br><span class="line">    <span class="keyword">if</span> (oldTab != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="comment">// 遍历数组（桶）</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">0</span>; j &lt; oldCap; ++j) &#123;</span><br><span class="line">            Node&lt;K,V&gt; e;</span><br><span class="line">            <span class="comment">// 若桶中不为空</span></span><br><span class="line">            <span class="keyword">if</span> ((e = oldTab[j]) != <span class="keyword">null</span>) &#123;</span><br><span class="line">                oldTab[j] = <span class="keyword">null</span>;</span><br><span class="line">                <span class="keyword">if</span> (e.next == <span class="keyword">null</span>)</span><br><span class="line">                    <span class="comment">// 重新计算节点在新HashMap桶数组的下标</span></span><br><span class="line">                    newTab[e.hash &amp; (newCap - <span class="number">1</span>)] = e;</span><br><span class="line">                <span class="keyword">else</span> <span class="keyword">if</span> (e <span class="keyword">instanceof</span> TreeNode)</span><br><span class="line">                    <span class="comment">// 如果是红黑树,判断是否需要链化</span></span><br><span class="line">                    ((TreeNode&lt;K,V&gt;)e).split(<span class="keyword">this</span>, newTab, j, oldCap);</span><br><span class="line">                <span class="keyword">else</span> &#123;</span><br><span class="line">                    <span class="comment">// 如果是链表</span></span><br><span class="line">                    Node&lt;K,V&gt; loHead = <span class="keyword">null</span>, loTail = <span class="keyword">null</span>;</span><br><span class="line">                    Node&lt;K,V&gt; hiHead = <span class="keyword">null</span>, hiTail = <span class="keyword">null</span>;</span><br><span class="line">                    Node&lt;K,V&gt; next;</span><br><span class="line">                    </span><br><span class="line">                    <span class="comment">// 遍历链表</span></span><br><span class="line">                    <span class="keyword">do</span> &#123;</span><br><span class="line">                        next = e.next;</span><br><span class="line">                        <span class="comment">// 判断扩容后是否需要移动位置</span></span><br><span class="line">                        <span class="keyword">if</span> ((e.hash &amp; oldCap) == <span class="number">0</span>) &#123;</span><br><span class="line">                            <span class="keyword">if</span> (loTail == <span class="keyword">null</span>)</span><br><span class="line">                                loHead = e;</span><br><span class="line">                            <span class="keyword">else</span></span><br><span class="line">                                loTail.next = e;</span><br><span class="line">                            loTail = e;</span><br><span class="line">                        &#125;</span><br><span class="line">                        <span class="keyword">else</span> &#123;</span><br><span class="line">                            <span class="keyword">if</span> (hiTail == <span class="keyword">null</span>)</span><br><span class="line">                                hiHead = e;</span><br><span class="line">                            <span class="keyword">else</span></span><br><span class="line">                                hiTail.next = e;</span><br><span class="line">                            hiTail = e;</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125; <span class="keyword">while</span> ((e = next) != <span class="keyword">null</span>);</span><br><span class="line">                    <span class="keyword">if</span> (loTail != <span class="keyword">null</span>) &#123;</span><br><span class="line">                        loTail.next = <span class="keyword">null</span>;</span><br><span class="line">                        newTab[j] = loHead;</span><br><span class="line">                    &#125;</span><br><span class="line">                    <span class="keyword">if</span> (hiTail != <span class="keyword">null</span>) &#123;</span><br><span class="line">                        hiTail.next = <span class="keyword">null</span>;</span><br><span class="line">                        newTab[j + oldCap] = hiHead;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> newTab;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上述过程代码一大串，其实就是确定容量和扩容两个步骤。</p>
<h3 id="2确认扩容大小">2.确认扩容大小</h3>
<h4 id="扩容的时机">扩容的时机</h4>
<p>在了解 HashMap 如何确认扩容大小之前，我们需要明白 HashMap 是什么时候会认为需要扩容。</p>
<p>我们在前面知道了，<strong>value 的下标由 key 的高低位混合后与数组长度-1进行与运算获得</strong>，也就是说，如果数组长度不够大——或者说<strong>容量不够大，就会导致与运算后得到的随机值范围受限，因此更可能造成哈希冲突</strong>。</p>
<p>为此，HashMap 引入负载系数 <code>loadFactor</code>，当不指定时默认为0.75，则有扩容阈值 <code>threshold = 容量*负载系数</code>，<strong>达到扩容阈值——而不是容量大小——的时候就会进行扩容</strong>。</p>
<p>假如我们都使用初始值，即默认容量16，默认负载系数0.75，则第一次扩容后，当元素个数达到 <code>0.75*16=12</code> 时，就会进行一次扩容变为原来的两倍，也就是32，并且将 <code>threshold</code>更新为<code>32*0.75=24</code>。如此反复。</p>
<h4 id="扩容的大小">扩容的大小</h4>
<p>扩容的时候，分为两种情况：已经扩容过，还未扩容过。</p>
<p>我们仅针对获取新容量 <code>newCap</code> 与新扩容阈值 <code>newThr</code> 这段代码逻辑，画出大致流程图：</p>
<img src="http://img.xiajibagao.top/未命名文件.jpg" alt="未命名文件" style="zoom:50%;">
<p>这里比较需要注意的是，<strong>当 oldCap 已经大于等于理论最大值的时候，会在设置 <code>newThr=Integer.MAX_VALUE</code>后直接返回，不会执行后序扩容过程</strong>。</p>
<p>另外，当新扩容阈值被设置为 <code>Integer.MAX_VALUE</code>以后，<strong>由于该值已经是最大的整数值了，所以设置为该值以后 HashMap 就不会再触发扩容了</strong>。</p>
<h3 id="3重哈希过程">3.重哈希过程</h3>
<p>我们知道，如果桶数组扩容了，那么数组长度也就变了，那么根据长度与哈希值进行与运算的时候计算出来的下标就不一样。在 JDK7 中 HashMap 扩容移动旧容器的数据的时候，会直接进行重哈希获得新索引，并且打乱所有元素的排布。<strong>而在JDK8进行了优化，只移动部分元素</strong>。</p>
<p>我们可以回去看看扩容部分的代码，其中有这两处判断：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 判断扩容后是否需要移动位置</span></span><br><span class="line"><span class="keyword">if</span> ((e.hash &amp; oldCap) == <span class="number">0</span>) &#123;</span><br><span class="line">    <span class="comment">//... ...</span></span><br><span class="line">&#125;<span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (hiTail == <span class="keyword">null</span>)</span><br><span class="line">        hiHead = e;</span><br><span class="line">    <span class="keyword">else</span></span><br><span class="line">        hiTail.next = e;</span><br><span class="line">    hiTail = e;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 扩容后移动位置</span></span><br><span class="line"><span class="keyword">if</span> (hiTail != <span class="keyword">null</span>) &#123;</span><br><span class="line">    hiTail.next = <span class="keyword">null</span>;</span><br><span class="line">    newTab[j + oldCap] = hiHead;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>前面有提到 HashMap 取下标，是通过将 key 的哈希值与长度做与运算，也就是 <code>(n-1) &amp; hash</code>，而这里通过计算 <code>n &amp; hash</code>是否为 0 判断是否需要位移。</p>
<p>他的思路是这样的：</p>
<p>假如从16扩容到32，扩容前通过<code>(n-1) &amp; hash</code> 取模是取后4位，而扩容后取后5位，因为01111和1111没区别，<strong>所以如果多出来这一位是0，那么最后用新长度去与运算得到的坐标是不变的，那么就不用移动</strong>。否则，多出来这一位相当于多了10000，<strong>转为十进制就是在原基础上加16，也就是加上了原桶数组的长度，那么直接在原基础上移动原桶数组长度就行了</strong>。</p>
<p>以初始容量 <code>oldCap = 16,newCap = 32</code> 为例，我们先看看他的换算过程：</p>
<table>
<thead>
<tr>
<th></th>
<th>十进制 Cap</th>
<th>二进制 Cap</th>
<th>二进制 Cap-1</th>
<th>十进制 Cap-1</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>oldCap</strong></td>
<td>16</td>
<td>10000</td>
<td>1111</td>
<td>15</td>
</tr>
<tr>
<td><strong>newCap</strong></td>
<td>32</td>
<td>100000</td>
<td>11111</td>
<td>31</td>
</tr>
</tbody>
</table>
<p>以上述数据为基础，我们模拟下面三个 key 在扩容过程中的计算：</p>
<table>
<thead>
<tr>
<th>key</th>
<th>hash</th>
<th>(oldCap-1) &amp; hash</th>
<th>oldCap &amp; hash</th>
<th>(newCap-1) &amp; hash</th>
</tr>
</thead>
<tbody>
<tr>
<td>808321199</td>
<td>110000001011100000000010101111</td>
<td>1111（15）</td>
<td>0</td>
<td>01111（15）</td>
</tr>
<tr>
<td>7015199</td>
<td>11010110000101100011111</td>
<td>1111（15）</td>
<td>10000</td>
<td>11111（31）</td>
</tr>
<tr>
<td>9999</td>
<td>10011100001111</td>
<td>1111（15）</td>
<td>0</td>
<td>01111（15）</td>
</tr>
</tbody>
</table>
<p>不难看出，<strong>只有当 <code>oldCap &amp; hash &gt; 0 </code>的时候元素才需要移动</strong>，而由于容量必然是2的冥，每次扩容新容量都是旧容量的两倍，换成二进制，相同的 hash 值与运算算出来的坐标总是多1，因此相当于每次需要移动的距离都是旧容量。</p>
<p><strong>也就是说，如果 <code>oldCap &amp; hash &gt; 0</code>，那么就有 <code>新坐标=原下标+oldCap</code></strong>，这个逻辑对应的代码就是 <code>newTab[j + oldCap] = hiHead;</code>这一行。</p>
<p>这样做的好处显而易见，<strong>少移动一些元素可以减少扩容的性能消耗，同时同一桶中的元素也有可能在重哈希之后被移动，使得哈希冲突得以在扩容后减缓，元素散列更均匀。</strong></p>
<h2 id="八-hashmap-获取元素">八、HashMap 获取元素</h2>
<p>和<code>put()</code>方法和 <code>putVal()</code>的关系一样，<code>get()</code>方法以及其他获取元素的方法最终都依赖于 <code>getNode()</code>方法。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> V <span class="title">get</span><span class="params">(Object key)</span> </span>&#123;</span><br><span class="line">    Node&lt;K,V&gt; e;</span><br><span class="line">    <span class="keyword">return</span> (e = getNode(hash(key), key)) == <span class="keyword">null</span> ? <span class="keyword">null</span> : e.value;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="1-getnode">1. getNode</h3>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">final</span> Node&lt;K,V&gt; <span class="title">getNode</span><span class="params">(<span class="keyword">int</span> hash, Object key)</span> </span>&#123;</span><br><span class="line">    Node&lt;K,V&gt;[] tab; Node&lt;K,V&gt; first, e; <span class="keyword">int</span> n; K k;</span><br><span class="line">    <span class="comment">// 如果桶数组不为空，并且桶中不为null</span></span><br><span class="line">    <span class="keyword">if</span> ((tab = table) != <span class="keyword">null</span> &amp;&amp; (n = tab.length) &gt; <span class="number">0</span> &amp;&amp;</span><br><span class="line">        (first = tab[(n - <span class="number">1</span>) &amp; hash]) != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="comment">// 如果桶中第一个元素的key与要查找的key相同，返回第一个元素</span></span><br><span class="line">        <span class="keyword">if</span> (first.hash == hash &amp;&amp; <span class="comment">// always check first node</span></span><br><span class="line">            ((k = first.key) == key || (key != <span class="keyword">null</span> &amp;&amp; key.equals(k))))</span><br><span class="line">            <span class="keyword">return</span> first;</span><br><span class="line">        <span class="comment">// 如果存在后续元素</span></span><br><span class="line">        <span class="keyword">if</span> ((e = first.next) != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="comment">// 如果已经转为红黑树，则使用红黑树进行查找</span></span><br><span class="line">            <span class="keyword">if</span> (first <span class="keyword">instanceof</span> TreeNode)</span><br><span class="line">                <span class="keyword">return</span> ((TreeNode&lt;K,V&gt;)first).getTreeNode(hash, key);</span><br><span class="line">            <span class="keyword">do</span> &#123;</span><br><span class="line">                <span class="comment">// 否则遍历链表</span></span><br><span class="line">                <span class="keyword">if</span> (e.hash == hash &amp;&amp;</span><br><span class="line">                    ((k = e.key) == key || (key != <span class="keyword">null</span> &amp;&amp; key.equals(k))))</span><br><span class="line">                    <span class="keyword">return</span> e;</span><br><span class="line">            &#125; <span class="keyword">while</span> ((e = e.next) != <span class="keyword">null</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="2为什么元素要同时重写equals和hashcode">2.为什么元素要同时重写equals和hashcode？</h3>
<p>首先，不被原本的的hashCode和equals是这样的</p>
<ul>
<li><code>hashCode()</code>是根据内存地址换算出来的一个值</li>
<li><code>equals()</code> 方法是判断两个对象内存地址是否相等</li>
</ul>
<p>我们回顾一下上文，可以看到无论<code>put()</code>还是<code>get()</code>都会有类似这样的语句：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// putVal</span></span><br><span class="line">p.hash == hash &amp;&amp; ((k = p.key) == key ||</span><br><span class="line">                   (key != <span class="keyword">null</span> &amp;&amp; key.equals(k)));</span><br><span class="line"><span class="comment">// getNode</span></span><br><span class="line">p.hash == hash &amp;&amp; (key != <span class="keyword">null</span> &amp;&amp; key.equals(k));</span><br></pre></td></tr></table></figure>
<p>因为可能存在哈希冲突，或者为 null 的 key，因此所以光判断哈希值是不够的，事实上，当我们试图添加或者找到一个 key 的时候，方法会根据三方面来确定一个唯一的 key：</p>
<ul>
<li>比较 <code>hashCode()</code>是否相等：代码是比较内部 <code>hash()</code>方法算出来的值 hash 是否相等，但是由于该方法内部还是调用 <code>hashCode()</code>，所以实际上是比较的仍然是<code>hashCode()</code>算出来的值；</li>
<li>比较 <code>equlas()</code>是否相等：<code>Object.equlas()</code>方法在不重写的时候，默认比较的是内存地址；</li>
<li>比较 key 是否为 null；</li>
</ul>
<p><strong>为什么要重写equals和hashcode方法？</strong></p>
<p>当我们使用 HashMap 提供的默认的流程时，这三处校验已经足以保证 key 是唯一的。但是这也带来了一些问题，当我们使用一些未重写了 <code>Object.hashCode()</code>或者 <code>Object.equlas()</code>方法的类的实例作为 key 的时候，由于 Object 类中的方法默认比较的都是内存地址，因此必须持有当初作为 key 的实例才能拿到 value。</p>
<p>我们举个例子：</p>
<p>假设我们有一个 Student 类</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Student</span> </span>&#123;</span><br><span class="line">    String name;</span><br><span class="line">    Integer age;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Student</span><span class="params">(String name, Integer age)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.name = name;</span><br><span class="line">        <span class="keyword">this</span>.age = age;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>现在我们使用 Student 的实例作为 key：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">Map&lt;Object,Object&gt; map = <span class="keyword">new</span> HashMap&lt;&gt;(<span class="number">2</span>);</span><br><span class="line">map.put(<span class="keyword">new</span> Student(<span class="string">&quot;xx&quot;</span>,<span class="number">16</span>), <span class="string">&quot;a&quot;</span>);</span><br><span class="line">map.put(<span class="keyword">new</span> Student(<span class="string">&quot;xx&quot;</span>,<span class="number">16</span>), <span class="string">&quot;a&quot;</span>);</span><br><span class="line"><span class="keyword">for</span>(Map.Entry&lt;Object, Object&gt; entry : map.entrySet())&#123;</span><br><span class="line">    System.out.print(entry.getValue());</span><br><span class="line">&#125;;</span><br><span class="line"><span class="comment">// aa</span></span><br></pre></td></tr></table></figure>
<p>因此，如果我们希望使用对象作为 key，那么大多数时候都需要重写<code>equals()</code>和<code>hashcode()</code>的。</p>
<p><strong>为什么要同时重写两个方法？</strong></p>
<p>这个也很好理解，判断 key 需要把 <code>equals()</code>和<code>hashcode()</code>两个的返回值都判断一遍，<strong>如果只重写其中一个，那么最后还是不会被认为是同一个 key</strong>。</p>
<p>当我们为 Student 重写 <code>equals()</code>和<code>hashcode()</code>以后，结果运行以后输出就是只有一个 a 了。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">hashCode</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>.name.hashCode() + age;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">equals</span><span class="params">(Object obj)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> obj <span class="keyword">instanceof</span> Student &amp;&amp;</span><br><span class="line">        <span class="keyword">this</span>.name.equals(((Student) obj).name);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="九-hashmap-删除元素">九、HashMap 删除元素</h2>
<p>在 HashMap 中，get，put 和 remove 行为各自都有一个统一的底层方法。在 <code>remove()</code> 中，这个方法就是 <code>removeNode()</code>，所有的删除行为最终都要通过调用它来实现。</p>
<h3 id="1-removenode">1. removeNode</h3>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">final</span> Node&lt;K,V&gt; <span class="title">removeNode</span><span class="params">(<span class="keyword">int</span> hash, Object key, Object value,</span></span></span><br><span class="line"><span class="function"><span class="params">                           <span class="keyword">boolean</span> matchValue, <span class="keyword">boolean</span> movable)</span> </span>&#123;</span><br><span class="line">    Node&lt;K,V&gt;[] tab; Node&lt;K,V&gt; p; <span class="keyword">int</span> n, index;</span><br><span class="line">    <span class="comment">// 若集合不为空</span></span><br><span class="line">    <span class="keyword">if</span> ((tab = table) != <span class="keyword">null</span> &amp;&amp; (n = tab.length) &gt; <span class="number">0</span> &amp;&amp;</span><br><span class="line">        (p = tab[index = (n - <span class="number">1</span>) &amp; hash]) != <span class="keyword">null</span>) &#123;</span><br><span class="line">        Node&lt;K,V&gt; node = <span class="keyword">null</span>, e; K k; V v;</span><br><span class="line">        <span class="comment">// 若桶中第一个就是目标元素</span></span><br><span class="line">        <span class="keyword">if</span> (p.hash == hash &amp;&amp;</span><br><span class="line">            ((k = p.key) == key || (key != <span class="keyword">null</span> &amp;&amp; key.equals(k))))</span><br><span class="line">            node = p;</span><br><span class="line">        <span class="comment">// 否则遍历链表/树删除节点</span></span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span> ((e = p.next) != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">if</span> (p <span class="keyword">instanceof</span> TreeNode)</span><br><span class="line">                node = ((TreeNode&lt;K,V&gt;)p).getTreeNode(hash, key);</span><br><span class="line">            <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="keyword">do</span> &#123;</span><br><span class="line">                    <span class="keyword">if</span> (e.hash == hash &amp;&amp;</span><br><span class="line">                        ((k = e.key) == key ||</span><br><span class="line">                         (key != <span class="keyword">null</span> &amp;&amp; key.equals(k)))) &#123;</span><br><span class="line">                        node = e;</span><br><span class="line">                        <span class="keyword">break</span>;</span><br><span class="line">                    &#125;</span><br><span class="line">                    p = e;</span><br><span class="line">                &#125; <span class="keyword">while</span> ((e = e.next) != <span class="keyword">null</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 若找到目标元素，并且确定要删除，就删除节点</span></span><br><span class="line">        <span class="keyword">if</span> (node != <span class="keyword">null</span> &amp;&amp; (!matchValue || (v = node.value) == value ||</span><br><span class="line">                             (value != <span class="keyword">null</span> &amp;&amp; value.equals(v)))) &#123;</span><br><span class="line">            <span class="keyword">if</span> (node <span class="keyword">instanceof</span> TreeNode)</span><br><span class="line">                <span class="comment">// 若要删除为红黑树节点</span></span><br><span class="line">                ((TreeNode&lt;K,V&gt;)node).removeTreeNode(<span class="keyword">this</span>, tab, movable);</span><br><span class="line">            <span class="keyword">else</span> <span class="keyword">if</span> (node == p)</span><br><span class="line">                <span class="comment">// 若要删除节点为链表头结点</span></span><br><span class="line">                tab[index] = node.next;</span><br><span class="line">            <span class="keyword">else</span></span><br><span class="line">                p.next = node.next;</span><br><span class="line">            ++modCount;</span><br><span class="line">            --size;</span><br><span class="line">            afterNodeRemoval(node);</span><br><span class="line">            <span class="keyword">return</span> node;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="2红黑树在删除过程的链化">2.红黑树在删除过程的链化</h3>
<p>在扩容部分我们了解了链表是如何转为红黑树的，事实上红黑树也可以在必要的时候转化为链表。在 <code>removeNode()</code>方法中，可以看到调用了 <code>removeTreeNode()</code>以删除红黑树节点，实际上在这个过程中会发生红黑树的链化。</p>
<p>我们暂且只关注链化的判断条件，也就是在 <code>removeTreeNode()</code>中的这一段代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 根节点为null，根节点的左或右子节点为null，根节点左子节点的左子节点为null</span></span><br><span class="line"><span class="keyword">if</span> (root == <span class="keyword">null</span> || root.right == <span class="keyword">null</span> ||</span><br><span class="line">    (rl = root.left) == <span class="keyword">null</span> || rl.left == <span class="keyword">null</span>) &#123;</span><br><span class="line">    tab[index] = first.untreeify(map);  <span class="comment">// too small</span></span><br><span class="line">    <span class="keyword">return</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>也就是说，如果可能存在的最小红黑树如下：</p>
<p><img src="http://img.xiajibagao.top/image-20201217204231973.png" alt="删除中可能存在的最小红黑树"></p>
<p>可以看到，此时树共有四个及节点，需要再删除一个节点才会导致链化，也就是说，在 remove 中，触发链化的最小树可能只有3个节点，而最大树需要考虑到变色和平衡，是十个（待考证）。</p>
<p>也就是说，和网上所说的小于6就链化不同，<strong>在删除中，链化触发值是一个范围，在 [3,10] 之间</strong>。</p>
<h3 id="3红黑树在扩容过程的链化">3.红黑树在扩容过程的链化</h3>
<p>我们知道，扩容经过重哈希有可能会拆分链表，树也一样。在扩容时， <code>split()</code>方法会对红黑树进行拆分，以便重哈希后变更位置，在里头有这么一段逻辑：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 左头结点不为空，并且长度小于链化阈值 6</span></span><br><span class="line"><span class="keyword">if</span> (lc &lt;= UNTREEIFY_THRESHOLD)</span><br><span class="line">    <span class="comment">// 将红黑树转为链表</span></span><br><span class="line">    tab[index] = loHead.untreeify(map);</span><br><span class="line"><span class="keyword">else</span> &#123;</span><br><span class="line">    tab[index] = loHead;</span><br><span class="line">    <span class="keyword">if</span> (hiHead != <span class="keyword">null</span>) <span class="comment">// (else is already treeified)</span></span><br><span class="line">        loHead.treeify(tab);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在扩容时，是否链化的标准就是<strong>树中元素个数是否小于链化阈值6</strong>。</p>
<h3 id="4为什么会存在两套链化逻辑">4.为什么会存在两套链化逻辑？</h3>
<p>关于为什么要选择不同的链化标准，网上也没有比较确定的答案，这里说说个人的猜测。</p>
<p>首先，不管是树化还是链化都比较消耗性能，应该需要尽量避免的，这个是前提条件。</p>
<p>链表的树化条件决定了当红黑树存在时，容器必然是比较大的，而容量越大，下一次扩容要达到扩容阈值就越难，换句话说，触发扩容的概率就越小。因而扩容本身就是一个低频操作，要在扩容的时候恰好因为重哈希导致树被拆分的概率就更小了，此时链化的判定条件就可以严格点，因此只要小于6就链化。</p>
<p>而删除是一个比较频繁的，而且带有主观意向的操作，很可能你一次删除的多个节点在哈希值刚好是连续的，也就是说，多次删除恰好删除的是同一颗树上的节点的概率是比较大的，因此，判断条件就应该尽可能不那么严格，避免频繁的触发链化。</p>
<h2 id="十-hashmap-的迭代">十、HashMap 的迭代</h2>
<p>由于 Map 集合本质上表示的是一组键值对之间的映射关系，并且 HashMap 的数据结构是数组+链表/树，因此 HashMap 集合并无法直接像 Collection 接口的实现类那样直接迭代。</p>
<p>而在本文的第四部分，我们了解了 HashMap 中的几个主要内部类，其中四大视图类就是其中三个集合视图的 KeySet，Values，EntrySet，与一个键值对视图 Entry。当我们要迭代 HashMap 的时候，就需要通过迭代三个集合视图来实现，并且通过 key，value 或者 Entry 对象来接受迭代得到的对象。</p>
<p>值得一提的是，<strong>和 ArrayList 一样，HashMap 也实现了 fast-fail 机制，因此最好不要在迭代的时候进行结构性操作。</strong></p>
<h3 id="1迭代器迭代">1.迭代器迭代</h3>
<p><strong>所有集合都可以通过迭代器迭代器</strong>（集合的增强 for 循环在编译以后也是迭代器跌迭代）。</p>
<p>所以，在 HashMap 中，三种视图集合都可以通过迭代器或增强 for 循环迭代器，但是 <strong>HashMap 本身虽然有迭代器，但是由于没有 <code>iterator()</code>方法，所以无法通过迭代器或者增强 for 直接迭代，必须通过三种视图集合来实现迭代。</strong></p>
<p>以 EntrySet 视图为例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">Map&lt;Object,Object&gt; map = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line"></span><br><span class="line"><span class="comment">// 迭代器</span></span><br><span class="line">Iterator&lt;Map.Entry&lt;Object, Object&gt;&gt; iterator = map.entrySet().iterator();</span><br><span class="line"><span class="keyword">while</span> (iterator.hasNext()) &#123;</span><br><span class="line">    Map.Entry&lt;Object, Object&gt; entry = iterator.next();</span><br><span class="line">    System.out.print(entry.getValue());</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 增强for迭代，等价于迭代器迭代</span></span><br><span class="line"><span class="keyword">for</span>(Map.Entry&lt;Object, Object&gt; entry : map.entrySet())&#123;</span><br><span class="line">    System.out.print(entry.getValue());</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">// forEach迭代</span></span><br><span class="line">map.entrySet().forEach(s -&gt; &#123;</span><br><span class="line">    System.out.println(s.getValue());</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p><code>KeySet</code> 视图和 <code>values</code>同理，但是 values 是 Collection 集合，所以写法会稍微有点区别。</p>
<h3 id="2视图集合中的数据从何处来">2.视图集合中的数据从何处来</h3>
<p>我们虽然通过 <code>entrySet()</code>，<code>values()</code>和 <code>keySet()</code>三个方法获取了视图集合并且迭代成功了，但是回头看源码，却发现源码中返回的只是一个空集合，里面并没有任何装填数据的操作，但是当我们直接拿到视图集合的时候，却能直接遍历，原因在于他们的迭代器：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">KeyIterator</span> <span class="keyword">extends</span> <span class="title">HashIterator</span></span></span><br><span class="line"><span class="class">    <span class="keyword">implements</span> <span class="title">Iterator</span>&lt;<span class="title">K</span>&gt; </span>&#123;</span><br><span class="line">    <span class="comment">// 获取迭代器返回的node的key</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">final</span> K <span class="title">next</span><span class="params">()</span> </span>&#123; <span class="keyword">return</span> nextNode().key; &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">ValueIterator</span> <span class="keyword">extends</span> <span class="title">HashIterator</span></span></span><br><span class="line"><span class="class">    <span class="keyword">implements</span> <span class="title">Iterator</span>&lt;<span class="title">V</span>&gt; </span>&#123;</span><br><span class="line">    <span class="comment">// 获取迭代器返回的node的value</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">final</span> V <span class="title">next</span><span class="params">()</span> </span>&#123; <span class="keyword">return</span> nextNode().value; &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">EntryIterator</span> <span class="keyword">extends</span> <span class="title">HashIterator</span></span></span><br><span class="line"><span class="class">    <span class="keyword">implements</span> <span class="title">Iterator</span>&lt;<span class="title">Map</span>.<span class="title">Entry</span>&lt;<span class="title">K</span>,<span class="title">V</span>&gt;&gt; </span>&#123;</span><br><span class="line">    <span class="comment">// 获取迭代器返回的node</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">final</span> Map.<span class="function">Entry&lt;K,V&gt; <span class="title">next</span><span class="params">()</span> </span>&#123; <span class="keyword">return</span> nextNode(); &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>而这个 <code>nextNode()</code>方法来自于他们的父类<code>HashIterator</code>，这里需要连着它的构造方法一起看：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 构造方法</span></span><br><span class="line">HashIterator() &#123;</span><br><span class="line">    expectedModCount = modCount;</span><br><span class="line">    Node&lt;K,V&gt;[] t = table;</span><br><span class="line">    current = next = <span class="keyword">null</span>;</span><br><span class="line">    index = <span class="number">0</span>;</span><br><span class="line">    <span class="comment">// 获取第一个不为空的桶中的第一个节点</span></span><br><span class="line">    <span class="keyword">if</span> (t != <span class="keyword">null</span> &amp;&amp; size &gt; <span class="number">0</span>) &#123; <span class="comment">// advance to first entry</span></span><br><span class="line">        <span class="keyword">do</span> &#123;&#125; <span class="keyword">while</span> (index &lt; t.length &amp;&amp; (next = t[index++]) == <span class="keyword">null</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// nextNode</span></span><br><span class="line"><span class="function"><span class="keyword">final</span> Node&lt;K,V&gt; <span class="title">nextNode</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    Node&lt;K,V&gt;[] t;</span><br><span class="line">    Node&lt;K,V&gt; e = next;</span><br><span class="line">    <span class="keyword">if</span> (modCount != expectedModCount)</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> ConcurrentModificationException();</span><br><span class="line">    <span class="keyword">if</span> (e == <span class="keyword">null</span>)</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> NoSuchElementException();</span><br><span class="line">    <span class="comment">// 接着构造方法获取到的第一个非空桶中的节点，遍历以该节点为头结点的链表</span></span><br><span class="line">    <span class="comment">// 当遍历完，接着查看下一个桶中的节点</span></span><br><span class="line">    <span class="keyword">if</span> ((next = (current = e).next) == <span class="keyword">null</span> &amp;&amp; (t = table) != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">do</span> &#123;&#125; <span class="keyword">while</span> (index &lt; t.length &amp;&amp; (next = t[index++]) == <span class="keyword">null</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> e;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>可以看到，这个 <strong>HashIterator 就是 HashMap 真正意义上的迭代器</strong>，<strong>它会从桶数组中第一个非空桶的第一个节点开始，迭代完全部桶数组中的每一个节点</strong>。但是它并不直接使用，而是作为而三个视图集合的迭代器的父类。</p>
<p>三个视图集合自己的迭代器通过把<code>HashIterator</code>的<code>nextNode()</code>方法的基础重新适配为 <code>next()</code>，分别把它从返回 Node 节点类变为了返回节点、节点的 key、节点的 value，这就是<strong>集合视图迭代的原理</strong>。</p>
<p>由于 Node 本身就携带了 key，value和 hash，因此删除或者添加就可以直接通过 HashMap 类的方法去操作，<strong>这就是迭代器增删改的原理</strong>。</p>
<h3 id="3-foreach迭代">3. forEach迭代</h3>
<p>HashMap 重写了 forEach() 方法，三个视图集合也自己重写了各自的 <code>forEach()</code>方法。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">forEach</span><span class="params">(BiConsumer&lt;? <span class="keyword">super</span> K, ? <span class="keyword">super</span> V&gt; action)</span> </span>&#123;</span><br><span class="line">    Node&lt;K,V&gt;[] tab;</span><br><span class="line">    <span class="keyword">if</span> (action == <span class="keyword">null</span>)</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> NullPointerException();</span><br><span class="line">    <span class="comment">// 若集合不为空</span></span><br><span class="line">    <span class="keyword">if</span> (size &gt; <span class="number">0</span> &amp;&amp; (tab = table) != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">int</span> mc = modCount;</span><br><span class="line">        <span class="comment">// 遍历桶</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; tab.length; ++i) &#123;</span><br><span class="line">            <span class="comment">// 遍历链表</span></span><br><span class="line">            <span class="keyword">for</span> (Node&lt;K,V&gt; e = tab[i]; e != <span class="keyword">null</span>; e = e.next)</span><br><span class="line">                action.accept(e.key, e.value);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (modCount != mc)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> ConcurrentModificationException();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><code>forEach()</code>逻辑与迭代器类似，但是写法更直白，就是遍历桶数组然后遍历桶数组中的链表。三个视图集合的 <code>forEach()</code>写法与 HashMap 的基本一样，这里就不再赘述了。</p>
<h2 id="十一-总结">十一、总结</h2>
<p><strong>结构与扩容</strong></p>
<p>HashMap 底层结构是数组+链表/红黑树。</p>
<p>HashMap 在不指定初始容量和负载系数的时候，默认容量为16，默认负载系数为0.75，扩容阈值为当前容量*负载系数，当容器中的元素数量大于等于扩容阈值的时候就会扩容为原来的两倍。</p>
<p><strong>树化与链化</strong></p>
<p>红黑树的树化一般发生在添加元素的时候。由于扩容本身就可以缓解哈希冲突，因此要让 HashMap 选择树化而不是优先扩容，需要同时满足两个条件：</p>
<ul>
<li>当容器中总元素的数量大于等于64；</li>
<li>添加元素后桶中链表长度大于等于8。</li>
</ul>
<p>此时会将链表转为红黑树。</p>
<p>而红黑树的链化既发生在扩容过程，也发生在删除过程，扩容过程中的链化触发条件是树的节点数量小于链化阈值6，而删除过程中的链化触发条件要求是左子节点、左子节点的左子节点或右子节点为null。由于可能存在的最小树或者最大树，因此在删除时链化触发值的范围处于 [3,10] 之间。</p>
<p><strong>哈希算法</strong></p>
<p>HashMap 获取下标的过程分两步：</p>
<ul>
<li>位运算混淆 hashCode 的高低位：<code>(h = key.hashCode()) ^ (h &gt;&gt;&gt; 16)</code>，作用是保证取模后的随机性；</li>
<li>与运算计算下标：<code>(n - 1) &amp; hash</code>，作用是取模获取下标。</li>
</ul>
<p>其中，长度之所以是2的冥，就是为了在此处将长度作为哈希值的低位掩码，巧妙实现取模效果。</p>
<p><strong>扩容重哈希</strong></p>
<p>假如从16扩容到32，扩容前通过<code>(n-1) &amp; hash</code> 取模是取后4位，而扩容后取后5位，因为01111和1111没区别，<strong>所以如果多出来这一位是0，那么最后用新长度去与运算得到的坐标是不变的，那么就不用移动</strong>。否则，多出来这一位相当于多了10000，<strong>转为十进制就是在原基础上加16，也就是加上了原桶数组的长度，那么直接在原基础上移动原桶数组长度就行了</strong>。</p>
<p>也就是说，一个桶中的链表，在扩容后可能会被拆成两条分散在两个桶中。</p>
<p><strong>迭代</strong></p>
<p>HashMap 本身有迭代器 <code>HashIterator</code>，但是没有 <code>iterator()</code>方法，所以无法直接通过增强 for 循环或者获取迭代器进行迭代，只能借助三个视图集合的迭代器或增强 for 来迭代器。但是视图迭代器本身也是 <code>HashIterator</code>子类，因此视图本身只是空集合，它的迭代能力来自于它们自己的迭代器的父类<code>HashIterator</code>。</p>
<p>HashMap 和他的三个集合视图都重写了 <code>forEach()</code>方法，所以可以通过 <code>forEach()</code>迭代器。</p>
<p>HashMap 也实现了 fast-fail 机制，因此最好不要在迭代的时候进行结构性操作。</p>
<p><strong>equals和hashCode方法</strong></p>
<p>HashMap 在<code>get()</code>和<code>set()</code>的时候都会通过 <code>Object.equals()</code> 和 <code>Object.hashCode()</code> 方法来确定唯一 key。由于默认使用的 Object 的实现比较是内存地址，因此使用自建对象作为 key 会很不方便，因此需要重写两个方法。但是由于校验唯一性的时候两个方法都会用到，因此若要重写<code>equals()</code>和<code>hashCode()</code>必须同时重写两个方法，不能重写其中一个。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/java/" rel="tag"># java</a>
          
            <a href="/tags/java%E9%9B%86%E5%90%88%E5%AE%B9%E5%99%A8/" rel="tag"># java集合容器</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/12/15/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/%E8%B5%84%E6%BA%90%E6%8E%A8%E8%8D%90%EF%BC%9A%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E5%8F%AF%E8%A7%86%E5%8C%96%E7%BD%91%E7%AB%99/" rel="next" title="资源推荐：数据结构可视化网站">
                <i class="fa fa-chevron-left"></i> 资源推荐：数据结构可视化网站
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/12/17/%E6%9D%82%E4%B8%83%E4%B9%B1%E5%85%AB/%E5%A6%82%E4%BD%95%E8%A7%A3%E5%86%B3next5%E4%B8%BB%E9%A2%98%E7%9B%AE%E5%BD%95%E6%97%A0%E6%B3%95%E8%B7%B3%E8%BD%AC%E7%9A%84%E9%97%AE%E9%A2%98/" rel="prev" title="如何解决next5主题目录无法跳转的问题">
                如何解决next5主题目录无法跳转的问题 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/Createsequence.jpg"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/%7C%7Carchive">
              
                  <span class="site-state-item-count">89</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">21</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%A6%82%E8%BF%B0"><span class="nav-text">概述</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%80-hashmap-%E7%9A%84%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84"><span class="nav-text">一、HashMap 的数据结构</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BA%8C-hashmap%E7%9A%84%E6%88%90%E5%91%98%E5%8F%98%E9%87%8F"><span class="nav-text">二、HashMap的成员变量</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1%E6%9D%A5%E8%87%AA%E7%88%B6%E7%B1%BB%E7%9A%84%E5%8F%98%E9%87%8F"><span class="nav-text">1.来自父类的变量</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2%E8%87%AA%E5%B7%B1%E7%9A%84%E5%8F%98%E9%87%8F"><span class="nav-text">2.自己的变量</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3%E6%89%A9%E5%AE%B9%E7%9B%B8%E5%85%B3%E7%9A%84%E5%8F%98%E9%87%8F%E5%92%8C%E5%B8%B8%E9%87%8F"><span class="nav-text">3.扩容相关的变量和常量</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%89-%E6%9E%84%E9%80%A0%E6%96%B9%E6%B3%95"><span class="nav-text">三、构造方法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1%E6%8C%87%E5%AE%9A%E5%AE%B9%E9%87%8F%E5%92%8C%E8%B4%9F%E8%BD%BD%E7%B3%BB%E6%95%B0"><span class="nav-text">1.指定容量和负载系数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2%E5%8F%AA%E6%8C%87%E5%AE%9A%E5%AE%B9%E9%87%8F"><span class="nav-text">2.只指定容量</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3%E4%B8%8D%E6%8C%87%E5%AE%9A%E4%BB%BB%E4%BD%95%E7%B3%BB%E6%95%B0"><span class="nav-text">3.不指定任何系数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4%E6%A0%B9%E6%8D%AE%E6%8C%87%E5%AE%9Amap%E9%9B%86%E5%90%88%E6%9E%84%E5%BB%BA"><span class="nav-text">4.根据指定Map集合构建</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%9B%9B-hashmap%E7%9A%84%E5%86%85%E9%83%A8%E7%B1%BB"><span class="nav-text">四、HashMap的内部类</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-node-treenode"><span class="nav-text">1. Node &#x2F; TreeNode</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-keyset-keyiterator"><span class="nav-text">2.  KeySet &#x2F; KeyIterator</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-values-valueiterator"><span class="nav-text">3. Values  &#x2F;  ValueIterator</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-entryset-entryiterator"><span class="nav-text">4. EntrySet  &#x2F;  EntryIterator</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-hashiterator"><span class="nav-text">5. HashIterator</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-spliterator"><span class="nav-text">6. Spliterator</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BA%94-hashmap-%E8%8E%B7%E5%8F%96%E6%8F%92%E5%85%A5%E4%B8%8B%E6%A0%87"><span class="nav-text">五、HashMap 获取插入下标</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-%E8%AE%A1%E7%AE%97%E5%93%88%E5%B8%8C%E5%80%BC"><span class="nav-text">1. 计算哈希值</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-%E8%AE%A1%E7%AE%97%E4%B8%8B%E6%A0%87"><span class="nav-text">2. 计算下标</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%B8%BA%E4%BB%80%E4%B9%88%E5%AE%B9%E9%87%8F%E9%9C%80%E8%A6%81%E6%98%AF2%E7%9A%84%E5%B9%82"><span class="nav-text">为什么容量需要是2的幂？</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%B8%BA%E4%BB%80%E4%B9%88%E8%A6%81hash%E8%A6%81%E6%B7%B7%E6%B7%86%E9%AB%98%E4%BD%8E%E4%BD%8D"><span class="nav-text">为什么要hash()要混淆高低位？</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%85%AD-hashmap-%E6%B7%BB%E5%8A%A0%E5%85%83%E7%B4%A0"><span class="nav-text">六、HashMap 添加元素</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-putval"><span class="nav-text">1. putVal</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2%E9%93%BE%E8%A1%A8%E7%9A%84%E6%A0%91%E5%8C%96"><span class="nav-text">2.链表的树化</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E9%93%BE%E8%A1%A8%E8%BD%AC%E4%B8%BA%E7%BA%A2%E9%BB%91%E6%A0%91%E7%9A%84%E6%9D%A1%E4%BB%B6"><span class="nav-text">链表转为红黑树的条件</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3%E4%B8%BA%E4%BB%80%E4%B9%88key%E5%8F%AF%E4%BB%A5%E4%B8%BAnull"><span class="nav-text">3.为什么key可以为null</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%83-hashmap-%E7%9A%84%E6%89%A9%E5%AE%B9"><span class="nav-text">七、HashMap 的扩容</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-resize"><span class="nav-text">1. resize</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2%E7%A1%AE%E8%AE%A4%E6%89%A9%E5%AE%B9%E5%A4%A7%E5%B0%8F"><span class="nav-text">2.确认扩容大小</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%89%A9%E5%AE%B9%E7%9A%84%E6%97%B6%E6%9C%BA"><span class="nav-text">扩容的时机</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%89%A9%E5%AE%B9%E7%9A%84%E5%A4%A7%E5%B0%8F"><span class="nav-text">扩容的大小</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3%E9%87%8D%E5%93%88%E5%B8%8C%E8%BF%87%E7%A8%8B"><span class="nav-text">3.重哈希过程</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%85%AB-hashmap-%E8%8E%B7%E5%8F%96%E5%85%83%E7%B4%A0"><span class="nav-text">八、HashMap 获取元素</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-getnode"><span class="nav-text">1. getNode</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2%E4%B8%BA%E4%BB%80%E4%B9%88%E5%85%83%E7%B4%A0%E8%A6%81%E5%90%8C%E6%97%B6%E9%87%8D%E5%86%99equals%E5%92%8Chashcode"><span class="nav-text">2.为什么元素要同时重写equals和hashcode？</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B9%9D-hashmap-%E5%88%A0%E9%99%A4%E5%85%83%E7%B4%A0"><span class="nav-text">九、HashMap 删除元素</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-removenode"><span class="nav-text">1. removeNode</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2%E7%BA%A2%E9%BB%91%E6%A0%91%E5%9C%A8%E5%88%A0%E9%99%A4%E8%BF%87%E7%A8%8B%E7%9A%84%E9%93%BE%E5%8C%96"><span class="nav-text">2.红黑树在删除过程的链化</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3%E7%BA%A2%E9%BB%91%E6%A0%91%E5%9C%A8%E6%89%A9%E5%AE%B9%E8%BF%87%E7%A8%8B%E7%9A%84%E9%93%BE%E5%8C%96"><span class="nav-text">3.红黑树在扩容过程的链化</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4%E4%B8%BA%E4%BB%80%E4%B9%88%E4%BC%9A%E5%AD%98%E5%9C%A8%E4%B8%A4%E5%A5%97%E9%93%BE%E5%8C%96%E9%80%BB%E8%BE%91"><span class="nav-text">4.为什么会存在两套链化逻辑？</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8D%81-hashmap-%E7%9A%84%E8%BF%AD%E4%BB%A3"><span class="nav-text">十、HashMap 的迭代</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1%E8%BF%AD%E4%BB%A3%E5%99%A8%E8%BF%AD%E4%BB%A3"><span class="nav-text">1.迭代器迭代</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2%E8%A7%86%E5%9B%BE%E9%9B%86%E5%90%88%E4%B8%AD%E7%9A%84%E6%95%B0%E6%8D%AE%E4%BB%8E%E4%BD%95%E5%A4%84%E6%9D%A5"><span class="nav-text">2.视图集合中的数据从何处来</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-foreach%E8%BF%AD%E4%BB%A3"><span class="nav-text">3. forEach迭代</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8D%81%E4%B8%80-%E6%80%BB%E7%BB%93"><span class="nav-text">十一、总结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Createsequence</span>

  
</div>






  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  


  <!-- 引入目录截取js -->
  <script type="text/javascript" src="/js/src/custom/custom.js"></script>
</body>
</html>
